package com.bringspring.system.permission.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bringspring.common.annotation.JsbosTask;
import com.bringspring.common.base.EnabledMarkEnum;
import com.bringspring.common.base.UserInfo;
import com.bringspring.common.util.StringUtils;
import com.bringspring.common.util.UserProvider;
import com.bringspring.system.external.service.SynPushToThirdQyService;
import com.bringspring.system.permission.entity.OrganizeEntity;
import com.bringspring.system.permission.entity.UserEntity;
import com.bringspring.system.permission.service.OrganizeService;
import com.bringspring.system.permission.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

import static com.bringspring.system.external.constant.WxCpSysConfigConsts.SYS_DELETE;
import static org.reflections.Reflections.log;

@Component
public class PermissionScheduleTask {
    Logger logger = LoggerFactory.getLogger(PermissionScheduleTask.class);
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private UserService userService;

    @Autowired
    private SynPushToThirdQyService synPushToThirdQyService;


    @Autowired
    private UserProvider userProvider;
    @Autowired
    private Executor threadPoolExecutor;
    @JsbosTask(fullName = "同步九州HR部门", description = "同步九州HR部门")
    public void scheduledHrDept() throws Exception {
        logger.info("每天8：30提醒当天所有日程");
        this.getHrAllDeptList();
    }

    @JsbosTask(fullName = "同步九州HR用户", description = "同步九州HR用户")
    public void scheduledHrUser() throws Exception {
        logger.info("=================同步九州HR用户开始==================");
        this.getHrUserList();
    }


    public JSONArray getHrAllDeptList() {
        logger.info("同步部门数据开始:");
        JSONArray objects = new JSONArray();
        try {
            JSONObject jsonObject = new JSONObject();
            JSONObject paramStr = new JSONObject();
            paramStr.put("interfaceCode", "orgs");
            jsonObject.put("paramStr", paramStr);
            String deptList = HttpRequest.post("http://hr.jiuzhouinvest.com:60000/thirdPlatformForeign/call/v2/orgs_email")
                    .header("Content-Type", "application/json")
                    .body(jsonObject.toJSONString())//表单内容
                    .timeout(10000)//超时，毫秒
                    .execute().body();
            JSONObject result = JSONObject.parseObject(deptList);
            if (result.getString("code").equals("200")) {
                objects = result.getJSONArray("data");
                List<OrganizeEntity> sysDepts = null;
                if (objects.size() > 0) {
                    sysDepts = organizeService.getList();
                }
                for (int i = 0; i < objects.size(); i++) {
                    JSONObject obj = objects.getJSONObject(i);

                    boolean b = sysDepts.stream().anyMatch(dept -> dept.getId().equals(obj.getString("origin_id")));
                    if (b) {
                        //父级ID\名称、排序变动时更新
                        boolean b2 = sysDepts.stream().anyMatch(dept -> dept.getId().equals(obj.getString("origin_id"))
                                &&(
                                !dept.getParentId().equals(obj.getString("parent_origin_id"))
                                ||!dept.getFullName().equals(obj.getString("name"))
                                ||dept.getSortCode() !=obj.getLong("show_order")
                                )&&ObjectUtil.isNotNull(dept.getDeleteMark()) &&dept.getDeleteMark()!=1
                                &&null!=obj.getInteger("is_failure")&&obj.getInteger("is_failure")==0);
                        //如果部门id，部门父级id,部门名称，任意一个不想等，则执行更新操作。
                        if(b2){
                            OrganizeEntity sysDept = organizeService.getInfo(obj.getString("origin_id"));
                            sysDept.setFullName(obj.getString("name"));
                            sysDept.setParentId(obj.getString("parent_origin_id"));
                            sysDept.setEnabledMark(1);
                            sysDept.setDeleteMark(obj.getInteger("is_failure"));
                            sysDept.setDeleteTime(new Date());
                            sysDept.setSortCode(obj.getLong("show_order"));
                            //更新数据
                            organizeService.update(sysDept.getId(),sysDept);
                        }

                        //删除状态变动时更新变动时更新
                        boolean deleteFlag = sysDepts.stream().anyMatch(dept -> dept.getId().equals(obj.getString("origin_id"))
                                && ObjectUtil.isNotNull(dept.getDeleteMark()) &&dept.getDeleteMark()==0
                                &&null!=obj.getInteger("is_failure")&&obj.getInteger("is_failure")==1);
                        if (deleteFlag) {

                            OrganizeEntity sysDept = organizeService.getInfo(obj.getString("origin_id"));
                            sysDept.setDeleteMark(1);
                            //更新数据
                            organizeService.updateById(sysDept);

                            UserInfo userInfo = userProvider.get();
                            threadPoolExecutor.execute(() -> {
                                try {
                                    //删除部门后判断是否需要同步到企业微信
                                    synPushToThirdQyService.deleteDepartmentSysToQy(userInfo, false, sysDept.getId(), "");
                                } catch (Exception e) {
                                    logger.error("删除部门后同步失败，异常：" + e.getMessage());
                                }
                            });
                        }
                    }else if(null!=obj.getInteger("is_failure")&&obj.getInteger("is_failure")!=1){
                            OrganizeEntity sysDept = new OrganizeEntity();
                            sysDept.setId(obj.getString("origin_id"));
                            sysDept.setFullName(obj.getString("name"));
                            sysDept.setParentId(obj.getString("parent_origin_id"));
                            sysDept.setCategory("department");
                            sysDept.setEnabledMark(obj.getInteger("status"));
                            sysDept.setSortCode(obj.getLong("show_order"));
                            sysDept.setDeleteMark(obj.getInteger("is_failure"));
                            sysDept.setDeleteTime(new Date());
                            logger.debug("同步部门数据开始:" + sysDept.getOrganizeId() + "-" + sysDept.getFullName() + "-" + sysDept.getParentId());
                            organizeService.create(sysDept);

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询所有部门出错:" + e.getMessage());
        } finally {
            return objects;
        }

    }
    public JSONArray getHrUserList() {
        logger.debug("查询hr系统最近5分钟修改的用户开始:");
        HashMap<String, Object> paramMap = new HashMap<>();
        int offset=5;
        if (offset != 0) {
            String updateDate = cn.hutool.core.date.DateUtil.formatDateTime(cn.hutool.core.date.DateUtil.offsetMinute(new Date(), offset));//当前时间偏移5分钟
            paramMap.put("updated_date", updateDate);
        }
        //测试 https://mdmuat.ganglongchina.com
        //测试 http://172.22.21.180:37080
        //生产 http://192.168.100.180
        JSONArray objects = new JSONArray();
        try {
            JSONObject jsonObject = new JSONObject();
            JSONObject paramStr = new JSONObject();
            paramStr.put("interfaceCode", "emp");
            jsonObject.put("paramStr", paramStr);

            String users = HttpRequest.post("http://hr.jiuzhouinvest.com:60000/thirdForeignInterface/call/orgs")
                    .header("Content-Type", "application/json")
                    .body(jsonObject.toJSONString())//表单内容
                    .timeout(10000)//超时，毫秒
                    .execute().body();
            JSONObject result = JSONObject.parseObject(users);

            logger.debug("查询hr系统最近修改的用户结束:" + result);
            if (result.getString("code").equals("200")) {
                objects = result.getJSONObject("data").getJSONArray("data");
                this.saveOrUpdate(objects);
            }
        } catch (Exception e) {
            logger.error("查询hr系统最近修改的用户出错:" + e.getMessage());
        } finally {
            return objects;
        }

    }
    public void saveOrUpdate(JSONArray emailAccounts) {
        for (int i = 0; i < emailAccounts.size(); i++) {
            JSONObject email = emailAccounts.getJSONObject(i);
            try {
                if (StrUtil.isEmpty(email.getString("work_email"))) {
                    continue;
                }

                if (email.getString("status").equals("-1")) {//预入职的不同步
                    continue;
                }
                UserEntity user = userService.getUserByAccount(email.getString("work_email"));

                if(email.getString("name").equals("张君")){
                    System.out.println("=============");
                }
                if (user != null && StringUtils.isNotEmpty(user.getEmail())) {
                    // 如果部门变了。那就修改用户部门
                    if (StringUtils.isNotEmpty(user.getOrganizeId())&&!user.getOrganizeId().equals(email.getString("org_origin_id"))) {
                        user.setOrganizeId(email.getString("org_origin_id"));
                        userService.update(user.getId(),user);

                    }
                    if (email.getString("status").equals("1")) {//离职
                        //离职删除
                        logger.info("离职删除邮箱" + email.getString("work_email") + ";dept_code:" + email.getString("org_origin_id") + ";" + email.toJSONString());
                        //逻辑删除
                        user.setEnabledMark(EnabledMarkEnum.NOT_ENABLE.getCode());//禁用
                        user.setDeleteMark(1);
                        user.setDeleteTime(new Date());
                        userService.update(user.getId(),user);
                            // 操作类型为空或系统删除，执行第三方同步。
                            UserInfo operatorUser = userProvider.get();
                        UserEntity finalUser = user;
                        threadPoolExecutor.execute(() -> {
                                try {
                                    //删除用户之后判断是否需要同步到企业微信
                                    synPushToThirdQyService.deleteUserSysToQy(operatorUser, false, finalUser.getId(), null);

                                } catch (Exception e) {
                                    log.error("删除用户之后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
                                }
                            });

                    }
                }

                if (null==user && StringUtils.isNotEmpty(email.getString("work_email"))
                    &&!email.getString("status").equals("1")
                ){
                    user = new UserEntity();
                    user.setRealName(email.getString("name"));
                    user.setAccount(email.getString("work_email"));
                    user.setEmail(email.getString("work_email"));
                    user.setOrganizeId(email.getString("org_origin_id"));
                    user.setCode(email.getString("emp_no"));
                    user.setEnabledMark(1);
                    user.setGender(0);
                    user.setOrganizeId(email.getString("org_origin_id"));
                    userService.create(user);
                }

            }catch (Exception e){
                e.printStackTrace();
                logger.error("同步邮箱出错:" + e.getMessage());
            }
        }

    }
}